/**
 * 全局操作
 * chrome open
 * open -a 'Google Chrome' --args -allow-file-access-from-files
 *  --disable-web-security
 */
Global = {
	backHome:function() {
		if (window.device
				&& device.platform
				&& (device.platform.toLowerCase() == 'android' || device.platform
						.toLowerCase() == 'amazon-fireos')) {
			navigator.app.backHistory();
		} else {
			window.history.go(-1);
		}
	},
	pages: {},
	loadPage: function(id, data) {
		var _page = '';
		var page = this.pages[id];
		if (page) {
			_page = this.compile(page, data);
		} else {
			var that = this;
			var _page = '';
			$.ajax({
				type: 'GET',
				async: false,
				callback: this.compile,
				tmpdata: data,
		    	url: "templates/" + id + ".html",
		    	success: function (tmpl){
			        var $tmpl = tmpl;
			        that.pages[id] = $tmpl;
			        _page = this.callback($tmpl, this.tmpdata);
		    	}
			});
		}
		if ('' != $.trim(_page)) {
			PAGE_SLIDER.slidePage($(_page));
		}
	},
	compile: function(tmp, data) {
		return Handlebars.compile(tmp)(data);
	},
	loadFragment: function(id, data) {
		var _page = '';
		var page = this.pages[id];
		if (page) {
			_page = this.compile(page, data);
		} else {
			var that = this;
			var _page = '';
			$.ajax({
				type: 'GET',
				async: false,
				callback: this.compile,
				tmpdata: data,
		    	url: "templates/" + id + ".html",
		    	success: function (tmpl){
			        var $tmpl = tmpl;
			        that.pages[id] = $tmpl;
			        _page = this.callback($tmpl, this.tmpdata);
		    	}
			});
		}
		return _page;
	},
	setItem: function(key, value) {
		setTimeout(function() {
        	window.localStorage.setItem(key, JSON.stringify(value));
        }, 0);
	},
	getItem: function(key) {
		return JSON.parse(window.localStorage.getItem(key));
	},
	/**
	 * 振动控制
	 */
	vibrate: function() {
		navigator.notification.vibrate(1000);
	},
	longToast: function (msg) {
		try {
			navigator.notification.longToast(msg);
		} catch(e) {}
	},
	shortToast: function (msg) {
		try {
			navigator.notification.longToast(msg);
		} catch(e) {}
	},
	confirm: function(message, resultCallback, title, buttonLabels) {
		try {
			navigator.notification.confirm(message, resultCallback, title, buttonLabels);
		} catch(e) {}
	},
	loading: function(block) {
		if (block) {
			$('.ui-loader').show();
		} else {
			window.setTimeout(function() {
				$('.ui-loader').show();
	        }, 0);
		}
	},
	loaded: function(block) {
		if (block) {
			$('.ui-loader').hide();
		} else {
			window.setTimeout(function() {
				$('.ui-loader').hide();
	        }, 0);
		}
	},
	dial: function(tel) {
		try {
			navigator.phone.dial(tel);
		} catch(e) {}
	},
	dialer: function() {
		this.dial('4008979727');
	},
	rotateImage: function(args) {
		/**
		 * 需要传递参数
		 * {imageId:'', canvasId: '', width: ''}
		 * @param args
		 */
		var img = document.getElementById(args.imageId);
		var height = img.height;
		var width = img.width;
		var step = img.getAttribute('step');
		if (step == null || step == 3) {
			step = -1;
		}
		step ++;
		img.setAttribute('step', step);
		var canvas = document.getElementById(args.canvasId);
		if (canvas == null) {
			canvas = document.createElement('canvas'); 
			canvas.setAttribute("id", args.canvasId);
		}
		var h, w;
        if (step % 2 == 0) {
        	h = args.width / width * height;
            w = args.width;
        } else {
        	w = args.width / width * height;
            h = args.width;
        }
		var h = (step % 2 == 0) ? (args.width / width * height) : args.width;
		var w = width * h / height;
		var context = canvas.getContext('2d');
		if (step == 0) {
			canvas.width = w;
			canvas.height = h;
			context.translate(0, 0);
		} else if (step == 1) {
			canvas.width = h;
			canvas.height = w;
			context.translate(canvas.width, 0);
		} else if (step == 2) {
			canvas.width = w;
			canvas.height = h;
			context.translate(canvas.width, canvas.height);
		} else if (step == 3) {
			canvas.width = h;
			canvas.height = w;
			context.translate(0, canvas.height);
		}
		context.rotate(step * 90 * Math.PI / 180);
		context.drawImage(img, 0, 0, w, h);
		return canvas;
	},
	loadImage: function(image, callback) {
		image.src = image.src;
		if (image.complete) {//如果图片已经存在于浏览器缓存，直接调用回调函数
			callback.call(image);
			return;//直接返回，不用再处理onload事件
		}
		image.onload = function() {//图片下载完毕时异步调用callback函数。
			callback.call(image);//将回调函数的this替换为Image对象  
		};
	},
	imageType: function(img) {//取出html img类型图片的类型
		var src = img.src;
		if (/^data:image\/(\w*);base64,.*/.test(src)) {
			src = src.substring(0, 30);
			var m = src.match(/^data:image\/(\w*);base64,.*/);
			return 'image/' + m[1].toLowerCase();
		}
		if (/.*\.(\w*)$/.test(src)) {
			var m = src.match(/.*\.(\w*)$/);
			return 'image/' + m[1].toLowerCase();
		}
		return 'image/png';
	},
	/**
	 * 取参数
	 * @param ps
	 * @returns {param}
	 */
	getParameters: function(ps) {
		var params = {};
		var e, a = /\+/g, r = /([^&;=]+)=?([^&;]*)/g, d = function(s) {
			return decodeURIComponent(s.replace(a, " "));
		};
		while (e = r.exec(ps)) {
			var key = d(e[1]);
			var value = d(e[2]);
			if (/^#.*/.test(key)) {
				params['#id'] = key.replace(/^#*/, '');
			} else {
				params[key] = value;
			}
		}
		return params;
	},
	/**
	 * 页面路由加载
	 */
	route: function() {
		Global.loading(true);
		var page;
		var hash = window.location.hash;
		var params = Global.getParameters(hash);
		if (params['#id']) {
			var id = params['#id'];
			Global.loadPage(id, $.extend({}, {
				headerName : HEADER_NAME[id],
				identify : new Date().getTime()
			}, params));
		} else {
			console.log('Cannot get hash identify, redirect to guide page.');
			Global.loadPage('guidepage', {
				headerName : HEADER_NAME['guidepage'],
				identify : new Date().getTime()
			});
		}
		Global.loaded(true);
	},
	isIphone: function() {
		if (/(iPhone|iPod|iPad)/i.test(navigator.userAgent)) {  
			return true;
		}
		return false;
	},
	isAndroid: function() {
		if (/(Android)/i.test(navigator.userAgent)) {  
			return true;
		}
		return false;
	},
	isMobile: function() {
		if (/(iPhone|iPod|iPad|Android|BlackBerry|IEMobile)/i.test(navigator.userAgent)) {  
			return true;
		}
		return false;
	}
};

/**
 * 依附在全局上的常量
 */
Global.loginKey = '__login_key__';//登录的标识